<template>
    <div class="page">
      <div class="page-body">
        <div class="toolbar">
          <div class="toolbar__left">
            <el-button type="info" @click="refresh">刷新</el-button>
            <el-button
              v-auth="'base:sys:user:add'"
              type="primary"
              @click="handleAdd"
              >新增</el-button
            >
            <el-button
              v-auth="'base:sys:user:delete'"
              type="danger"
              :disabled="checkedIds.length <= 0"
              @click="handleDelete(checkedIds)"
            >
              删除
            </el-button>
          </div>
          <div class="toolbar__right"></div>
        </div>
        <div class="table">
          <el-table
            v-loading="loading"
            border
            :data="tableData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="头像" prop="headImg">
              <template #default="{ row }">
                <img class="avatar" :src="row.headImg" />
              </template>
            </el-table-column>
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="昵称" prop="nickName" />
            <el-table-column label="角色" prop="roleName">
              <template #default="{ row }">
                <el-space>
                  <el-tag v-for="item in row.roleName">
                    {{ item }}
                  </el-tag>
                </el-space>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status">
              <template #default="{ row }">
                <el-switch
                  :modelValue="!!row.status"
                  @update:modelValue="handleUpdateStatus($event, row.id)"
                />
              </template>
            </el-table-column>
            <el-table-column label="手机号码" prop="phone" />
            <el-table-column label="备注" prop="remark" />
            <el-table-column label="创建时间" prop="createTime">
              <template #default="{ row }">
                <p>{{ dateFormat(row.createTime, "YYYY") }}</p>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="right">
              <template #default="{ row }">
                <el-button
                  v-auth="'base:sys:user:update'"
                  type="default"
                  size="small"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-popconfirm
                  title="你确认要删除吗？"
                  @confirm="handleDelete(row.id)"
                >
                  <template #reference>
                    <el-button type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="query.page"
            v-model:page-size="query.size"
            background
            layout="prev, pager, next, sizes"
            :page-sizes="[1, 2, 3, 4]"
            :total="total"
          />
        </div>
      </div>
  
      <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="750"
        destroy-on-close
      >
        <UpsertForm
          ref="upsertForm"
          @cancel="handleCancel"
          @success="handleSuccess"
        />
      </el-dialog>
    </div>
  </template>


<script>
import { ElMessage } from "element-plus";
import { getUserPage, delUser, updUser } from "@/api/user";
import UpsertForm from "./components/upsert-form.vue";
import dateMixin from "@/mixins/date-mixin";

export default {
  name: "UserList",
  mixins: [dateMixin],
  components: {
    UpsertForm,
  },

  data() {
    return {
      loading: false,
      tableData: [],
      total: 0, // 数据总条数
      checkedIds: [],
      dialog: {
        visible: false,
        title: "新增",
      },
      // 查询相关的参数
      query: {
        page: 1, // 当前页码
        size: 2, // 每页显示条数
      },
    }
  },

  watch: {
    query: {
      handler() {
        this.refresh();
      },
      deep: true,
    },
  },
  methods: {
    /**
     * 处理状态变更
     */
    handleUpdateStatus(value, id) {
      console.log("value", value, id);
      updUser({
        id,
        status: value ? 1 : 0,
      }).then(() => {
        ElMessage.success("更新成功");
        this.refresh();
      });
    },
    /**
     * 处理勾选
     */
    handleSelectionChange(rows) {
      // console.log("rows", rows);
      this.checkedIds = rows.map((item) => item.id);
    },

    /**
     * 获取数据
     */
    refresh() {
      this.loading = true;
      getUserPage(this.query)
        .then((data) => {
          // data => {list: [], pagination: { page, size, total }}
          this.tableData = data.list;
          this.total = data.pagination.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 新增按钮点击
     */
    handleAdd() {
      this.dialog.title = "新增";
      this.dialog.visible = true;
    },

    /**
     * 编辑按钮点击
     */
    handleEdit(row) {
      console.log("row", row);
      this.dialog.title = "编辑";
      this.dialog.visible = true;

      this.$nextTick(() => {
      this.$refs.upsertForm.setModel({
          ...row,
          roleIdList : row.roleIdList !== null && row.roleIdList .split(",").map((id) => +id),
        });
      });
    },

    /**
     * 处理删除
     */
    handleDelete(id) {
      delUser({
        ids: Array.isArray(id) ? id : [id],
      }).then(() => {
        ElMessage.success("删除成功");
        this.refresh();
      });
    },

    /**
     * 处理新增与编辑时的取消
     */
    handleCancel() {
      this.dialog.visible = false;
    },

    /**
     * 处理新增与编辑时的成功
     */
    handleSuccess() {
      ElMessage.success("成功");
      this.dialog.visible = false;
      // 更新数据
      this.refresh();
    },
  },

  created() {
    this.refresh();
  },
}
</script>

<style lang="scss" scoped>
.page-search {
  height: 100px;
  border: 1px solid #000;
}

.page-body {
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  &__left {
    flex: 1;
  }
  &__right {
    width: 100px;
    height: 36px;
    background-color: green;
  }
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.avatar {
  display: block;
  width: 40px;
  height: 40px;
}
</style>
